﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 服务端双缓冲队列
{
    class SingleBufferingQueue
    {
        public static SingleBufferingQueue _instance;

        public static SingleBufferingQueue Create()
        {
            return _instance ?? (_instance = new SingleBufferingQueue());
        }

        private readonly Queue<string> _waitExecData;

        public bool IsRuning { get; set; }

        private SingleBufferingQueue()
        {
            IsRuning = true;
            if (_waitExecData == null)
                _waitExecData = new Queue<string>();
        }

        public void Init(int threadCount)
        {
            for (var i = 0; i < threadCount; i++)
            {
                //Task.Factory.StartNew(DoWork);
            } 
        }

        public void DoWork()
        {
            while (IsRuning)
            {
                try
                {
                    Execute();
                }
                catch
                {

                }
            }
        }

        private void Execute()
        {
            string val = string.Empty;
            lock (_waitExecData)
            {
                if (_waitExecData.Count > 0)
                {
                   val=  _waitExecData.Dequeue();
                    //Console.Write();
                }
            }

            ///
            if (string.IsNullOrEmpty(val))
            {
                return;
            }

            Interlocked.Add(ref  RecordNum, 1);
            if (RecordNum >= MaxRun)
            {
                IsRuning = false;
            }
        }


        public void Push(string message)
        {
            lock (_waitExecData)
            {
                _waitExecData.Enqueue(message);
            }
        }

        public long RecordNum = 0;

        public long MaxRun = 100;
    }
}
